package main

import (
	"fmt"
	"sync"
)

var (
	counter1 int
	rwMutex  sync.RWMutex
)

func read(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	rwMutex.RLock() // 读锁
	fmt.Printf("Goroutine %d read counter: %d\n", id, counter1)
	rwMutex.RUnlock() // 释放读锁
}

func write(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	rwMutex.Lock() // 写锁
	counter1++
	fmt.Printf("Goroutine %d incremented counter to: %d\n", id, counter1)
	rwMutex.Unlock() // 释放写锁
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go read(i, &wg)
	}

	wg.Add(1)
	go write(100, &wg)

	wg.Wait()
}
